<?php

namespace App\Models\Bureau;

use App\Jobs\Bureau\BureauGeoCodeRegeoJob;
use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class WxBureau extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_bureau';

    protected $appends = ['least_price_tip'];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {

        });

        static::created(function ($model) {
            if($model->type == 3){
                WxBureau::where('id', $model->id)->update([
                    'least_price' => WxBureauGroup::where('bureau_id', $model->id)->min('cost_per_team')
                ]);
            }else{
                WxBureau::where('id', $model->id)->update([
                    'least_price' => WxBureauGroup::where('bureau_id', $model->id)->min('cost_per_person')
                ]);
            }
            BureauGeoCodeRegeoJob::dispatch($model->id);
        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'status') {
                    $originalValue = $original[$key];

                    if($originalValue == 1){
                        if($model->status == 1){

                        }else if($model->status === 0){
                            UserUtils::add_user_notice(9002, $model->user_id,'新建组局活动审核被驳回','您新建的「<a href="/pagesZ/organize-bureau/details/index?id='.$model->id.'">'.StrUtils::limit($model->title).'</a>」被驳回，详情请咨询客服',100);
                        }
                    }else if($originalValue === 0){
                        if($model->status == 1){
                            UserUtils::add_user_notice(9002, $model->user_id,'新建组局活动审核通过','您新建的「<a href="/pagesZ/organize-bureau/details/index?id='.$model->id.'">'.StrUtils::limit($model->title).'</a>」已经审核通过，快去分享给朋友们吧',100);
                        }else{

                        }
                    }
                }else if($key == 'longitude' || $key == 'latitude'){
                    BureauGeoCodeRegeoJob::dispatch($model->id);
                }
            }

            if($model->type == 3){
                WxBureau::where('id', $model->id)->update([
                    'least_price' => WxBureauGroup::where('bureau_id', $model->id)->min('cost_per_team')
                ]);
            }else{
                WxBureau::where('id', $model->id)->update([
                    'least_price' => WxBureauGroup::where('bureau_id', $model->id)->min('cost_per_person')
                ]);
            }
        });

        static::deleted(function ($model) {
            WxBureauGroup::where('bureau_id', $model->id)->delete();
            WxChat::where('expand_type', 103)->where('expand_id', $model->id)->forceDelete();
        });
    }

    public function setImageUrlsAttribute($value)
    {
        global $__MINI_GLOBAL_REQUEST_ENV__;
        if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
            $image_urls = is_array($value) ? $value : json_decode($value, true);
            if(_empty_($image_urls)){
                $this->attributes['image_urls'] = '[]';
            }
            $image_urls_new = [];
            foreach ($image_urls as $img_url){
                $img_info = ImageUtils::get_url_img_info($img_url);
                $obj = [
                    'url' => $img_url,
                    'width' => 0,
                    'height' => 0
                ];
                if($img_info){
                    $obj['width'] = $img_info['width'];
                    $obj['height'] = $img_info['height'];
                }
                $image_urls_new[] = $obj;
            }
            if($image_urls_new){
                $this->attributes['image_urls'] = json_encode($image_urls_new);
            }else{
                $this->attributes['image_urls'] = '[]';
            }
        }else{
            $this->attributes['image_urls'] = $value;
        }
    }

    public function getImageUrlsAttribute($value)
    {
        global $__MINI_GLOBAL_REQUEST_ENV__;
        if($__MINI_GLOBAL_REQUEST_ENV__ == 'web'){
            $image_urls = [];
            if($value){
                if(is_string($value)){
                    $image_urls = json_decode($value, true);
                }
            }else{
                $image_urls = [];
            }
            $image_urls_arr = [];
            if($image_urls){
                foreach ($image_urls as $image_url){
                    $image_urls_arr[] = $image_url['url'];
                }
            }
            return json_encode($image_urls_arr);
        }
        if(_empty_($value)){
            return [];
        }
        return json_decode($value, true);
    }

    public function getUserInfoFillAttribute($value)
    {
        if(_empty_($value)){
            return [];
        }
        return json_decode($value, true);
    }

    public function getLeastPriceTipAttribute($value)
    {
        if(_empty_($this->city)){
            BureauGeoCodeRegeoJob::dispatch($this->id);
        }
        if($this->least_price > 0){
            $formatted = sprintf("%.2f", $this->least_price);
            // 检查小数部分是否全为0
            if (substr($formatted, -3) === '.00') {
                // 去掉小数部分
                return '￥'.substr($formatted, 0, -3).'起';
            }else{
                return '￥'.$this->least_price.'起';
            }
        }
        return '免费';
    }



    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

}
